(function($) {
	$.fn.pager = function(options) {
		var opts = $.extend({}, $.fn.pager.defaults, options);
		return this.each(function() {
			$(this).empty().append(
					renderpager(parseInt(options.pagenumber),
							parseInt(options.pagecount),
							options.buttonClickCallback,
							parseInt(options.totalcount)));
			$('.pagination li').mouseover(function() {
				document.body.style.cursor = "pointer";
			}).mouseout(function() {
				document.body.style.cursor = "auto";
			});
		});
	};

	function renderpager(pagenumber, pagecount, buttonClickCallback, totalcount) {
		var $pager = $('<ul class="pagination"></ul>');
		$pager.append(renderButton(
				"<a href='javascript:void(0);'>上一页</a>", pagenumber, pagecount, buttonClickCallback));
		var startPoint = 1;
		var endPoint = 9;
		var thpoint = "<li class='item'><span>...</span></li>";
		if (pagenumber > 4) {
			startPoint = pagenumber - 4;
			endPoint = pagenumber + 4;
		}
		if (endPoint > pagecount) {
			startPoint = pagecount - 8;
			endPoint = pagecount;
			thpoint = "";
		}
		if (startPoint < 1) {
			startPoint = 1;
		}
		for (var page = startPoint; page <= endPoint; page++) {
			var currentButton = $("<li class='item'><a href='javascript:void(0);'>" + (page)
					+ "</a></li>");
			page == pagenumber ? currentButton.addClass('active')
					: currentButton.click(function() {
						buttonClickCallback(this.firstChild.firstChild.data);
					});
			currentButton.appendTo($pager);
		}
		$pager.append(thpoint).append(
				renderButton("<a href='javascript:void(0);'>下一页</a>",
						pagenumber, pagecount, buttonClickCallback));
		$pager.append('<li class="item news-number">当前共有<i>'+totalcount+'</i>条</li>');
		return $pager;
	}

	function renderButton(buttonLabel, pagenumber, pagecount,
			buttonClickCallback) {
		var $Button = $('<li class="item">' + buttonLabel + '</li>');
		var destPage = 1;
		switch (buttonLabel) {
		case "<a href='javascript:void(0);'>上一页</a>":
			destPage = pagenumber - 1;
			break;
		case "<a href='javascript:void(0);'>下一页</a>":
			destPage = pagenumber + 1;
			break;
		}
		//console.log(destPage);
		if (buttonLabel == "<a href='javascript:void(0);'>上一页</a>") {
			pagenumber <= 1 ? $Button.addClass('previous') : $Button.click(function() {
						buttonClickCallback(destPage);
					});
		} else {
			$Button.addClass('next');
			$Button.click(function() {
				buttonClickCallback(destPage);
			});
		}
		return $Button;
	}

	$.fn.pager.defaults = {
		pagenumber : 1,
		pagecount : 1
	};
})(jQuery);